package system

import (
	"github.com/gin-gonic/gin"
	"liuche17.cn/go-blog/server/global"
	"liuche17.cn/go-blog/server/model"
	"liuche17.cn/go-blog/server/model/common/resp"
	sysMode "liuche17.cn/go-blog/server/model/system/resp"
)

type DashBoardApi struct{}

// GetStatistics 获取后台仪表盘基础统计信息
func (s *DashBoardApi) GetStatistics(c *gin.Context) {
	// 得到文章数量
	var articleInfos []model.Article
	err := global.GB_DB.Model(&model.Article{}).Where("is_deleted != ?", 1).Scan(&articleInfos).Error
	if err != nil {
		resp.Fail(c)
		return
	}
	// 得到文章总访问量
	articlePvCount := func(articles []model.Article) int {
		var count = 0
		for _, article := range articles {
			count += article.ReadNum
		}
		return count
	}
	// 得到分类总数
	var categoryCount int64
	err = global.GB_DB.Model(&model.Category{}).Count(&categoryCount).Error
	if err != nil {
		resp.Fail(c)
		return
	}
	// 得到标签总数
	var tagCount int64
	err = global.GB_DB.Model(&model.Tag{}).Count(&tagCount).Error
	if err != nil {
		resp.Fail(c)
		return
	}

	res := sysMode.DashBoardInfo{
		ArticleTotalCount:  len(articleInfos),
		CategoryTotalCount: int(categoryCount),
		TagTotalCount:      int(tagCount),
		PvTotalCount:       articlePvCount(articleInfos),
	}

	resp.OkWithData(res, c)
}

// GetDateArticlePublishCount 获取后台仪表盘文章发布热点统计信息
func (s *DashBoardApi) GetDateArticlePublishCount(c *gin.Context) {
	// 得到最近半年发布文章信息
	resMap, err := dashboardService.GetHalfYearArticlePublishInfo()
	if err != nil {
		resp.Fail(c)
		return
	}

	resp.OkWithData(resMap, c)
}

// GetWeekArticlePVCount 得到每周文章访问次数
func (s *DashBoardApi) GetWeekArticlePVCount(c *gin.Context) {
	resList, err := dashboardService.GetWeekArticlePV()
	if err != nil {
		resp.FailWithMessage(err.Error(), c)
		return
	}
	resp.OkWithData(resList, c)
}
